package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private WorkspaceService  workspaceService;

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //数据封装返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户数据统计
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //select count(id) from user where create_time < ? and create_time >?
        List<Integer> newUserList = new ArrayList<>();
        //select count(id) from user where create_time < ?
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",endTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);

        }

        return UserReportVO.builder()
               .dateList(StringUtils.join(dateList,","))
               .totalUserList(StringUtils.join(totalUserList,","))
               .newUserList(StringUtils.join(newUserList,","))
               .build();
    }

    /**
     * 订单数据统计
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //select count(id) from orders where status = ? and order_time < ? and order_time > ?
        List<Integer> validOrderCountList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer validOrderCount = getOrderCount(Orders.COMPLETED, beginTime, endTime);
            validOrderCountList.add(validOrderCount);
            Integer orderCount = getOrderCount(null, beginTime, endTime);
            orderCountList.add(orderCount);
        }
        //计算时间区间内的订单总数量stream流
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的订单完成率
        Double orderCompletionRate =0.0 ;
        if(!totalOrderCount.equals(0)){
             orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }
        return OrderReportVO.builder()
               .dateList(StringUtils.join(dateList,","))
               .orderCountList(StringUtils.join(orderCountList,","))
               .validOrderCountList(StringUtils.join(validOrderCountList,","))
               .totalOrderCount(totalOrderCount)
               .validOrderCount(validOrderCount)
               .orderCompletionRate(orderCompletionRate)
               .build();
    }

    private Integer getOrderCount(Integer status, LocalDateTime begin, LocalDateTime end) {
        Map map = new HashMap();
        map.put("status",status);
        map.put("begin",begin);
        map.put("end",end);
        return orderMapper.countByMap(map);
    }

    /**
     * 销量排名Top10
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //日期不用封装到List中，横坐标不是日期，是名称nameList
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> names= goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names,",");
        List<Integer> numbers = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers,",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出营业报表Excel
     */
    @Override
    public void exportBusinessData(HttpServletResponse response){
        //1.查询数据库， 获取营业数据--查询最近30天的营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        //查询概览数据部分
        BusinessDataVO businessDataVo = workspaceService.getBusinessData(begin, end);

        //2.通过POI将数据写到Excel中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        
        //基于已有的模板文件创建一个新的Excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据 概览数据
            //1.时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin + "至" + dateEnd);
            //第四行
            //2.营业额
            sheet.getRow(3).getCell(2).setCellValue(businessDataVo.getTurnover());
            //3.订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessDataVo.getOrderCompletionRate());
            //4.新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessDataVo.getNewUsers());
            //第五行
            //5.有效订单数
            sheet.getRow(4).getCell(2).setCellValue(businessDataVo.getValidOrderCount());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessDataVo.getUnitPrice());

            //填充数据 每天的明细数据
            for( int i = 0; i < 30; i++){
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获得某行
                XSSFRow row = sheet.getRow(7 + i);
                //1.日期
                row.getCell(1).setCellValue(date.toString());
                //2.营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //3.有效订单数
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //4.订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //5.平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //6.新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }


            // 3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}